package main

import (
	"fmt"
	"log"
	"net/http"
	"runtime"
	"strings"
	"time"
)

//1.接收客户端request,并将request中带的header写入response header.
func Homework1(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //获取请求参数
	if len(r.Header) > 0 {
		for k, v := range r.Header {
			//fmt.Printf("request_header: %s=%s\n", k, v[0])
			w.Header().Add(k, v[0])
			//w.Header().Set("jesse", "devops")
		}
	}
	//2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	getVersion := runtime.Version()
	w.Header().Add("VERSION", getVersion)

	fmt.Println((strings.Repeat("-", 70)))
	w.WriteHeader(200)
	fmt.Fprintf(w, "Hi Go,I have received your http request.")
	//3.Server端记录访问日志包括客户端IP/HTTP返回码，输出到server端的标准输出
	IP := GetIP(r)
	curTime := time.Now().Format("2006-01-02 15:04:05")
	curPath := "/higo"
	fmt.Printf("request_time: %v client ip:%v http_status:%v url_path:%v\n", curTime, IP, http.StatusOK, curPath)
}

func GetIP(r *http.Request) string {
	forward := r.Header.Get("X-FORWARDED-FOR")
	if forward != "" {
		//fmt.Printf("client_ip: %v\n", forward)
		return forward
	} else {
		//fmt.Printf("client_ip: %v\n", r.RemoteAddr)
		return r.RemoteAddr
	}
}

//4.当访问localhost/healthz时，应返回200.
func Healthz(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprintf(w, "200")
	IP := GetIP(r)
	curTime := time.Now().Format("2006-01-02 15:04:05")
	curPath := "/healthz"
	fmt.Printf("request_time: %v client ip:%v http_status:%v url_path:%v\n", curTime, IP, http.StatusOK, curPath)
}

func main() {
	http.HandleFunc("/higo", Homework1)
	http.HandleFunc("/healthz", Healthz)
	err := http.ListenAndServe("0.0.0.0:80", nil)
	if err != nil {
		log.Fatal("ListenAndServe err:", err)
	}
}
